package com.lht.admin.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.commons.lang.StringUtils;

import java.io.InputStream;

/**
 * @author: Frank
 * @date: 2019/12/11 16:28
 * @version: V1.0
 */
public class OssUtils {

    //todo 上线修改
    private static final String SEPARATOR = "/";
    private static final int RANDOM_LENGTH = 4;
    public static final String BASE_PROCESS = "?x-oss-process=image/format,jpg";
    public static final String REAL_URL_BASE = "https://ffsb-tmp.oss-cn-shenzhen.aliyuncs.com/";
    public static final String END_POINT = "oss-cn-shenzhen.aliyuncs.com";
    public static final String ACCESS_KEY_ID = "LTAI4FxBsCJ6kGxnhRRmuzHc";
    public static final String ACCESS_KEY_SECRET = "qb5sE0C6olS1HLeL82JolpGZNGIvLd";
    public static final String BUC_KEY = "ffsb-tmp";

    public static String put(String staticKey, InputStream inputStream) {
        OSSClient client = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        PutObjectRequest request = new PutObjectRequest(BUC_KEY, staticKey, inputStream, null);
        client.putObject(request);
        client.shutdown();
        return new StringBuilder().append(REAL_URL_BASE).append(staticKey).append(BASE_PROCESS).toString();
    }

    public static String getStaticKey(String rootDirName, long userId, String format, String targetFolder) {
        StringBuffer sb = new StringBuffer();
        sb.append(rootDirName).append(SEPARATOR)
                .append(userId).append(SEPARATOR)
                .append(targetFolder).append(SEPARATOR)
                .append(System.currentTimeMillis())
                .append(RandomUtils.createRandom(RANDOM_LENGTH))
                .append(".").append(format);
        return sb.toString();
    }

    public static String getFileNameByKey(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        String[] split = key.split(SEPARATOR);
        int length = split.length;
        if (length <= 1) {
            return key;
        }
        return split[length - 1];
    }
}
